/* eslint-disable @typescript-eslint/no-explicit-any */
/* eslint-disable no-restricted-globals */
import dayjs from 'dayjs';
import quarterOfYear from 'dayjs/plugin/quarterOfYear';
import weekOfYear from 'dayjs/plugin/weekOfYear';

dayjs.extend(quarterOfYear);
dayjs.extend(weekOfYear);

/**
 * @description 格式化日期
 * @export
 * @param {string} val
 * @param {('year' | 'quarter' | 'month' | 'week' | 'day')} format
 * @returns {*}  {string}
 */
export function formatDate(
  val: string,
  format: 'year' | 'quarter' | 'month' | 'week' | 'day',
): string {
  let value = val;
  const date = new Date(val);
  if (!val || isNaN(date.getTime())) return value;
  const year = dayjs(date).year();
  switch (format) {
    case 'year':
      value = `${year}`;
      break;
    case 'quarter':
      value = `${year} ${dayjs(date).quarter()}季度`;
      break;
    case 'month':
      value = `${year} ${dayjs(date).month() + 1}月`;
      break;
    case 'week':
      value = `${year} ${dayjs(date).week()}周`;
      break;
    case 'day':
      value = dayjs(date).format('YYYY-MM-DD');
      break;
    default:
      break;
  }
  return value;
}

/**
 * @description 获取日期范围
 * @export
 * @param {string} val
 * @param {('year' | 'quarter' | 'month' | 'week' | 'yearweek' | 'day')} format
 * @returns {*}  {({
 *       start: string;
 *       end: string;
 *     }
 *   | undefined)}
 */
export function getDateRange(
  val: string,
  format?: string,
):
  | {
      start: string;
      end: string;
    }
  | undefined {
  if (
    !val ||
    isNaN(new Date(val).getTime()) ||
    !format ||
    !['year', 'quarter', 'month', 'week', 'yearweek', 'day'].includes(format)
  )
    return;
  let date = dayjs(val);
  const type: 'year' | 'quarter' | 'month' | 'week' | 'day' =
    format === 'yearweek' ? 'week' : (format as any);
  switch (type) {
    case 'year':
      date = date.year(date.year());
      break;
    case 'quarter':
      date = date.quarter(date.quarter());
      break;
    case 'month':
      date = date.month(date.month());
      break;
    case 'week':
      date = date.week(date.week());
      break;
    case 'day':
      date = date.date(date.date());
      break;
    default:
      break;
  }
  return {
    start: date.startOf(type).format('YYYY-MM-DD HH:mm:ss'),
    end: date.endOf(type).format('YYYY-MM-DD HH:mm:ss'),
  };
}
